import axios from 'axios'
import store from '@/store'
// 引入路由
import router from '@/router'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://ihrm-java.itheima.net',
  timeout: 5000 // request timeout
})

// 响应拦截器
service.interceptors.response.use(response => {
  if (response.data.success) {
    // 操作成功
    return response.data
  } else {
    // 如果success为false 业务出错,直接触发reject
    // 被catch分支捕获
    return Promise.reject(response.data.message)
  }
}, error => {
  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.commit('user/removeToken')
    // 2. 回到登陆页
    router.push('/login?return_tru=' + router.currentRoute.fullPath)
  }

  return Promise.reject(error)
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    // 如果当前存有token,就加在请求头上
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  }
  , error => {
    return Promise.reject(error)
  })
export default service
